
package net.vinote.smart.platform.module.database;

import java.util.HashMap;
import java.util.Map;

import net.vinote.smart.platform.exception.PlatformException;


/**
 * SerialNO管理器,用于生成表中serialNo字段的数值
 * 
 * @author 郑俊伟
 * 
 */
public class SerialNoManager
{
	private static SerialNoManager manage;

	/**
	 * 主键生成策略map，key:doNo,value:生成器
	 */
	private Map<String, PrimaryKeyGenerateStrategy> strategyMap;

	// private int maxSize = PlatformConst.Number.TEN;

	private SerialNoManager()
	{

	}

	public static SerialNoManager getInstance()
	{
		if (manage == null)
		{
			synchronized (SerialNoManager.class)
			{
				if (manage == null)
				{
					manage = new SerialNoManager();
					manage.strategyMap = new HashMap<String, PrimaryKeyGenerateStrategy>();
				}
			}
		}
		return manage;
	}

	public String getSerialNo(String table)
	{
		PrimaryKeyGenerateStrategy strategy = getStrategy(DefaultPrimaryKeyStrategy.class
				.getName());
		strategy.setTableName(table);
		return strategy.getSerialNo();
	}

	public PrimaryKeyGenerateStrategy getStrategy(String clazz)
	{
		PrimaryKeyGenerateStrategy strategy = strategyMap.get(clazz);
		if (strategy == null)
		{
			synchronized (PrimaryKeyGenerateStrategy.class)
			{
				if (strategy == null)
				{
					try
					{
						Object obj = Class.forName(clazz).newInstance();
						if (obj instanceof PrimaryKeyGenerateStrategy)
						{
							strategy = (PrimaryKeyGenerateStrategy) obj;
							strategyMap.put(clazz, strategy);
						}
						else
						{
							throw new PlatformException(
									"invalid PrimaryKeyGenerateStrategy " + obj);
						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
					strategyMap.put(clazz, strategy);
				}
			}
		}
		return strategy;
	}

	/*
	 * public int getMaxSize() { return maxSize; }
	 * 
	 * public void setMaxSize(int maxSize) { this.maxSize = maxSize; int length
	 * = String.valueOf(maxSize).length(); StringBuffer sb = new StringBuffer();
	 * while (length-- > 0) { sb.append("0"); } format = new
	 * DecimalFormat(sb.toString()); }
	 */
}
